// 轮播图组件 - 实现自动无缝循环轮播
const bannerCarousel = {
  template: `
    <div id="myCarousel" class="sui-carousel slide">
<!--      <ol class="carousel-indicators">-->
<!--        <li -->
<!--          v-for="(item, index) in bannerItems" -->
<!--          :key="index"-->
<!--          data-target="#myCarousel" -->
<!--          :data-slide-to="index" -->
<!--          :class="{ active: currentRealIndex === index }"-->
<!--          @click="goToSlide(index)"-->
<!--        ></li>-->
<!--      </ol>-->
      <div class="carousel-inner" @mouseenter="pauseCarousel" @mouseleave="startCarousel">
        <div 
          class="carousel-wrapper" 
          :style="{ transform: 'translateX(' + translateX + 'px)', transition: transitionDuration }"
          @transitionend="handleTransitionEnd"
        >
          <div 
            v-for="(item, index) in displayItems" 
            :key="'banner-' + index"
            class="item"
            :class="{ active: index === currentIndex }"
          >
            <a>
              <img :src="item.image" @click="search1" :alt="item.title" style="width: 100%; height: 100%; object-fit: cover; display: block;"/>
</a>
          </div>
        </div>
      </div>
<!--      <a href="#myCarousel" data-slide="prev" class="carousel-control left" @click.stop="prevSlide">&lt;</a>-->
<!--      1<a href="#myCarousel" data-slide="next" class="carousel-control right" @click.stop="nextSlide">&gt;</a>-->
    </div>
  `,
  name: "bannerCarousel",
  data() {
    return {
      bannerItems: [
        { id: 1, image: './img/banner1.jpg', title: '轮播图1' },
        { id: 2, image: './img/banner2.jpg', title: '轮播图2' },
        { id: 3, image: './img/banner3.jpg', title: '轮播图3' }
      ],
      currentIndex: 0, // 当前显示的索引（包含克隆项）
      currentRealIndex: 0, // 当前真实的索引（用于指示器）
      carouselInterval: null,
      intervalTime: 3500, // 轮播间隔时间（毫秒）
      translateX: 0,
      itemWidth: 0, // 每个item的实际像素宽度
      transitionDuration: 'transform 0.5s ease-in-out',
      isTransitioning: false // 防止过渡期间的重复操作
    }
  },
  computed: {
    // 用于显示的items，包含前后克隆项以实现无缝循环
    displayItems() {
      if (this.bannerItems.length === 0) return [];
      
      const items = [];
      const originalItems = this.bannerItems;
      
      // 前面添加最后一个项目的克隆（用于向左无缝切换）
      items.push({
        ...originalItems[originalItems.length - 1],
        isClone: true,
        cloneType: 'prev'
      });
      
      // 添加所有原始项目
      originalItems.forEach(item => {
        items.push({ ...item, isClone: false });
      });
      
      // 后面添加第一个项目的克隆（用于向右无缝切换）
      items.push({
        ...originalItems[0],
        isClone: true,
        cloneType: 'next'
      });
      
      return items;
    }
  },
  mounted() {
    this.initializeCarousel();
    window.addEventListener('resize', this.handleResize);
    
    // 尝试从服务器加载轮播图数据
    this.loadBannerData();
  },
  beforeDestroy() {
    this.pauseCarousel();
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 从服务器加载轮播图数据
    loadBannerData() {
      // 由于是模拟环境，这里直接使用默认数据
      // 实际项目中可以通过axios请求后端API
      /*
      axios.get("/banners")
        .then(resp => {
          if (resp && resp.length > 0) {
            this.bannerItems = resp;
            this.$nextTick(() => {
              this.initializeCarousel();
            });
          }
        })
        .catch(err => {
          console.log('获取轮播图数据失败:', err);
        });
      */
    },

    search1() {
        window.location = '../search.html';
    },
    
    // 初始化轮播
    initializeCarousel() {
      // 获取轮播项的宽度
      this.$nextTick(() => {
        const itemElement = document.querySelector('.carousel-wrapper .item');
        if (itemElement) {
          this.itemWidth = itemElement.offsetWidth;
          // 默认显示第一个真实项目（索引为1，因为索引0是克隆的最后一项）
          this.currentIndex = 1;
          this.currentRealIndex = 0;
          this.translateX = -this.itemWidth * this.currentIndex;
          // 启动自动轮播
          this.startCarousel();
        }
      });
    },
    
    // 启动自动轮播
    startCarousel() {
      if (this.carouselInterval) {
        clearInterval(this.carouselInterval);
      }
      this.carouselInterval = setInterval(() => {
        this.nextSlide();
      }, this.intervalTime);
    },
    
    // 暂停自动轮播
    pauseCarousel() {
      if (this.carouselInterval) {
        clearInterval(this.carouselInterval);
        this.carouselInterval = null;
      }
    },
    
    // 切换到上一张
    prevSlide() {
      if (this.isTransitioning) return;
      
      this.isTransitioning = true;
      this.transitionDuration = 'transform 0.5s ease-in-out';
      this.currentIndex--;
      this.translateX = -this.itemWidth * this.currentIndex;
    },
    
    // 切换到下一张
    nextSlide() {
      if (this.isTransitioning) return;
      
      this.isTransitioning = true;
      this.transitionDuration = 'transform 0.5s ease-in-out';
      this.currentIndex++;
      this.translateX = -this.itemWidth * this.currentIndex;
    },
    
    // 跳转到指定幻灯片
    goToSlide(index) {
      if (this.isTransitioning) return;
      
      this.isTransitioning = true;
      this.transitionDuration = 'transform 0.5s ease-in-out';
      this.currentIndex = index + 1; // +1 是因为前面有一个克隆项
      this.currentRealIndex = index;
      this.translateX = -this.itemWidth * this.currentIndex;
    },
    
    // 处理过渡结束事件
    handleTransitionEnd() {
      // 处理无缝循环逻辑
      if (this.currentIndex === 0) {
        // 如果滚动到了最前面的克隆项，无声地切换到真实的最后一项
        this.transitionDuration = 'none';
        this.currentIndex = this.bannerItems.length;
        this.currentRealIndex = this.bannerItems.length - 1;
        this.translateX = -this.itemWidth * this.currentIndex;
      } else if (this.currentIndex === this.bannerItems.length + 1) {
        // 如果滚动到了最后面的克隆项，无声地切换到真实的第一项
        this.transitionDuration = 'none';
        this.currentIndex = 1;
        this.currentRealIndex = 0;
        this.translateX = -this.itemWidth * this.currentIndex;
      } else {
        // 更新真实索引
        this.currentRealIndex = this.currentIndex - 1;
      }
      
      this.isTransitioning = false;
    },
    
    // 处理窗口大小变化
    handleResize() {
      // 重新计算轮播项宽度
      const itemElement = document.querySelector('.carousel-wrapper .item');
      if (itemElement) {
        this.itemWidth = itemElement.offsetWidth;
        this.translateX = -this.itemWidth * this.currentIndex;
      }
    }
  }
};

// 注册组件
Vue.component('banner-carousel', bannerCarousel);